﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace LandandSurvey
{
    public partial class AddLargePlan : System.Web.UI.Page
    {
        protected void Page_Load( object sender, EventArgs e )
        {
            if ( !IsPostBack )
            {
                if ( !HasPermission() )
                {
                    Response.Redirect( "ErrorPermission.aspx?returnurl=AddLargePlan.aspx" );
                }
            }
        }

        public bool HasPermission()
        {
            if ( Session[ "user.loggedin" ] == null )
            {
                return false;
            }
            if ( Session[ "user.loggedin" ].ToString() == "true" )
            {
                landsdbEntities container = new landsdbEntities();
                string username = Session[ "user.name" ].ToString();
                AppUser user = ( from i in container.AppUsers
                                 where i.UserName == username
                                 select i ).ToList().FirstOrDefault();
                if ( user != null )
                {
                    if ( user.UploadFiles == true )
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        protected void btnAdd_Click( object sender, EventArgs e )
        {
            landsdbEntities context = new landsdbEntities();

            PlanItem planitem = new PlanItem();
            planitem.Acreage = txtAcreage.Text;
            planitem.DateSigned = txtDateSigned.Text;
            planitem.FileName = "N/A";
            planitem.Location = txtLocation.Text;
            planitem.Owner = txtOwner.Text;
            planitem.PlanReference = txtPlanReference.Text;
            planitem.SheetNumber = txtSheetNumber.Text;
            planitem.Surveyor = txtSurveyor.Text;

            context.PlanItems.AddObject( planitem );
            try
            {
                context.SaveChanges();
                ClearForm();
                lblMessage.InnerText = "Plan added successfully";
            }
            catch
            {
                lblMessage.InnerText = "Error adding Plan";
            }
        }

        private void ClearForm()
        {
            txtAcreage.Text = "";
            txtDateSigned.Text = "";
            txtLocation.Text = "";
            txtOwner.Text = "";
            txtPlanReference.Text = "";
            txtSheetNumber.Text = "";
            txtSurveyor.Text = "";
        }
    }
}